var app=getApp()
var util = require('../../../utils/util.js')
var api = require('../../../config/api.js')
var QQMapWX = require('../../../utils/qqmap-wx-jssdk'); // 引入 SDK 文件
var qqmapsdk; // SDK实例对象
Page({
  data: {
    flag:0,
// 用户地址列表
    useraddresslist:[],
    // listuser
    listaddress:{},
    // 展示
    showaddress:false,
    // 存储用户的收货地址
    setaddressdata:{
      id:'',
      username:'',
      phone:'',
      address:'',
  },
    isShowAreaSelect: false,
    areaList: {
      // 变量名称是 van-area 规定写死的，不能换！不能换！不能换！
      province_list: {}, //省
      city_list: {},  //市
      county_list: {} //区
    },
    // 设置
    areaset:'',
  },
  onLoad: function (options) {//此处接收传递过来的参数wx.navigateTo跳转时传递的参数
    // 获取地址
    let addresslist=wx.getStorageSync('addresslist');
    let id=options.id;
    console.log(options)
    console.log('id:',id)
    let address={}
    addresslist.forEach(item=>{
      if (item.id==id){
        address['id']=item.id;
        address['username']=item.username;
        address['phone']=item.phone;
        address['address']=item.address;
      }
    })
    console.log('address:',address)
      // useraddress.push(address)
      this.setData({
        listaddress:address,
        areaset:address['address']
      })
      this.attached()
    // 获取地址
    // let addresslist=wx.getStorageSync('addresslist');
    // if(addresslist.length==0){
    //   this.setData({
    //     showaddress:true
    //   })
    //   this.attached()
    // }else{
    //   this.setData({
    //     showaddress:false,
    //     useraddresslist:addresslist
    //   })
    // }
  },
  // 加载数据
    attached() {
      //创建SDK实例
      qqmapsdk = new QQMapWX({
        key: 'OW7BZ-V43KK-LJQJX-AHYQQ-BCP26-ENF7U'
      });
      //调用 getCityList 
      qqmapsdk.getCityList({
        success: (res) => { //成功后的回调
          console.log('省份数据：', res.result[0][0]); //打印省份数据
          console.log('城市数据：', res.result[1][0]); //打印城市数据
          // console.log('区县数据：', res.result[2]); //打印区县数据
          this.setData({
            "areaList.province_list": this.ArrayToObject(res.result[0]),
            "areaList.city_list": this.ArrayToObject(res.result[1]),
            "areaList.county_list": this.ArrayToObject(res.result[2]),
          })
        },
        fail: function (error) {
          console.error(error);
        },
        complete: function (res) {
          console.log(res);
        }
      });
    },
    //确认选择
    confirmArea(e) {
      const values = e.detail.values
      console.log('values:',values)
      //直辖市，需要处理数据，保持省市一致，例如，省：北京市；市：北京市；区：朝阳区
      if (values.some(x => !Boolean(x)))[values[1], values[2]] = [values[0], values[1]];
      const arr = (values.map(x => x.name))
      //调用父组件的传递方法，并传递选择结果。
      console.log('arr:',arr)
      // 设置地址
      let areas=''
      arr.forEach((item,index) => {
        // console.log(item)
        areas+=item
      });
      console.log(areas)
      this.triggerEvent("confirm", arr)
      this.setData({
        areaset:areas,
        isShowAreaSelect: false,
      })
    },

    //关闭省市区选择组件
    closeAreaSelect() {
      this.setData({
        isShowAreaSelect: false
      })
    },

    //打开省市区选择组件
    showAreaSelect() {
      this.setData({
        isShowAreaSelect: true
      })
    },

   // 格式化省市区数据
    ArrayToObject(arr) {
      const obj = {}
      for (let i = 0; i < arr.length; i++) {
        obj[arr[i].id] = arr[i].fullname
      }
      return obj
    },
    // 选择所在地
    addarea(){
      this.showAreaSelect()
    },
    // 提交
    
    saveaddress(e){
      let flag=this.data.flag;
      // if(flag==1){
        let id=e.currentTarget.dataset.id;
        let useraddress=this.data.setaddressdata;
        console.log('id:',id)
        util.request(api.UpdateUserAddress,{
          id:id,
          useraddress:useraddress
        },"PUT").then(res=>{
          console.log(res)
          if(res.errno==0){
            console.log(res)
          }
        })
      // }else{

      // }
      
      let listaddress=wx.getStorageSync('addresslist');
      // let aid=e.currentTarget.dataset.id;
      // let useraddress=this.data.setaddressdata;
      listaddress.forEach((item,index)=>{
        console.log('item:',item.id)
        if(id==item.id){
          item.username=useraddress.username,
          item.phone=useraddress.phone,
          item.address=useraddress.address
        }
      })
      

      this.setData({
        useraddresslist:listaddress,
        username:'',
        phone:'',
        areaset:'',
        xiangxi:''
      })
      wx.setStorageSync('addresslist', listaddress)
      wx.navigateBack({
        delta: 1,
      })
    },
// 删除
    deladdress(e){
      let id=e.currentTarget.dataset.id;
      console.log('e',e)
      console.log('id:',id)
      util.request(api.DeleteUserAddress,{
        id:id
      },"DELETE").then(res=>{
        if(res.errno==0){
          console.log(res)
        }
      })
      let useraddresslist=wx.getStorageSync('addresslist');
      // let indexlist;
      // useraddresslist.forEach((item,index)=>{
      //   if (item.id==id){
      //     indexlist=index
      //   }
      // });
      let indexlist=useraddresslist.map(item=>{
        if(item.id!=id){
          return item
        }
      })
      indexlist=indexlist.filter(item=>item);
      console.log('index:',indexlist)
      // useraddresslist.splice(indexlist,1);
      wx.setStorageSync('addresslist', '')
      wx.setStorageSync('addresslist', indexlist)
      this.setData({
        areaset:''
      })
      wx.navigateBack({
        delta: 1,
      })
    },

    onChange(e){
      console.log('e:',e)
    },
    // 获取用户名
    nameinput(e){
      let username='setaddressdata.username'
      let sid='setaddressdata.id'
      let id=e.currentTarget.dataset.id;
      console.log('e:',id)
      let name=e.detail.value
      this.setData({
        [username]:name,
        [sid]:id,
        flag:1
      })
    },
    // 获取手机号
    phoneinput(e){
      let setphone='setaddressdata.phone'
      let phone=e.detail.value
      this.setData({
        [setphone]:phone
      })
    },
    // 获取所在地
    addareainput(e){
      var addresstemp=e.detail.value
      this.setData({
        areaset:addresstemp
      })
    },
    // 详细地址
    xiangxiinput(e){
      let addresstemp=e.detail.value
      let address= this.data.areaset+addresstemp
      // let uuid='setaddressdata.uuid'
      // let wxuuid=util.wxuuid();
      // console.log('wxuuid:',wxuuid);
      let setaddress='setaddressdata.address'
      // console.log('setaddress:',setaddress)
      this.setData({
        [setaddress]:address,
        // [uuid]:wxuuid
      })

      console.log('setaddress:',this.data.setaddressdata)
    },
    // x修改地址
    addressedit(e){
      wx.navigateTo({
        url: '/pages/me/editaddress/editaddress',
      })
    }
})